package com.example.moduleutils;


import android.icu.util.Calendar;
import android.os.Environment;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2022/12/21 11:42
 */
public class WriteLogUtil {
  public  static final String cacheDir= Environment.getExternalStorageDirectory().getAbsolutePath();

  public static final String PATH_LOG = cacheDir + "/Log";
  public static final String LOG_FILE_NAME = ".txt";
  private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  public static int sendUeTimes;
  public static int receiverUeTimes;
  public static int failureUeTimes;
  public static int successUeTimes;
  /**
   * 是否写入日志文件
   */
  public static final boolean LOG_WRITE_TO_FILE = true;

  /**
   * 错误信息
   */
  public static void e(String TAG, String msg) {
    if (LOG_WRITE_TO_FILE) {
      writeLogtoFile("e", TAG, msg);
    }
  }

  /**
   * 警告信息
   */
  public static void w(String TAG, String msg) {
    if (LOG_WRITE_TO_FILE) {
      writeLogtoFile("w", TAG, msg);
    }
  }

  /**
   * 调试信息
   */
  public static void d(String TAG, String msg) {
    if (LOG_WRITE_TO_FILE) {
      CachedThreadPoolSingleton.getInstance().execute(new Runnable() {
        @Override
        public void run() {
          try {
            writeLogtoFile("d", TAG, msg);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });
    }
  }

  /**
   * 提示信息
   */
  public static void i(String TAG, String msg) {
    if (LOG_WRITE_TO_FILE) {
      writeLogtoFile("i", TAG, msg);
    }
  }

  /**
   * 写入日志到文件中
   */
  private static void writeLogtoFile(String logType, String tag, String msg) {
    isExist(PATH_LOG);
    String needWriteMessage =
        "\r\n" + TimeUtil.getAllTime() + "\r\n" + logType + "  " + tag + "  " + msg + "\r\n";
    try {
      String filePre = formatter.format(new Date());
      File file = new File(PATH_LOG, filePre + LOG_FILE_NAME);
      if (!file.exists()) {
        file.createNewFile();
      }
      CachedThreadPoolSingleton.getInstance().execute(new Runnable() {
        @Override
        public void run() {
          try {
            FileWriter filerWriter = new FileWriter(file, true);
            BufferedWriter bufWriter = new BufferedWriter(filerWriter);
            bufWriter.write(needWriteMessage);
            bufWriter.newLine();
            bufWriter.close();
            filerWriter.close();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      });

    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 删除日志文件
   */
  public static void delFile() {

    File file = new File(PATH_LOG, LOG_FILE_NAME);
    if (file.exists()) {
      file.delete();
    }
  }

  /**
   * 判断文件夹是否存在,如果不存在则创建文件夹
   */
  public static void isExist(String path) {
    File file = new File(path);
    if (!file.exists()) {
      file.mkdirs();
    }
  }




  /**
   * clear count
   */
  public static void clearCount(){
    sendUeTimes=0;
    failureUeTimes=0;
    successUeTimes=0;
    receiverUeTimes=0;
  }
  /**
   * 删除七天之前的日志文件
   */
  public static void deleteFileBeforeSevenDays() {

    File file1 = new File(PATH_LOG);
    File[] files = file1.listFiles();// 读取

    if (files != null) {// 先判断目录是否为空，否则会报空指针
      for (File file : files) {
        String fileName = file.getName();
        if (fileName.endsWith(".txt")) {
          try {
            String s = fileName.substring(0, fileName.lastIndexOf("."));
            if (daysBetween(s.trim(), getStringToday()) >= 7) {
              file.delete();
            }
          } catch (ParseException e) {
            e.printStackTrace();

          }// 当前时间
        }
//        }
      }
    }
  }

  /**
   * 得到现在时间
   *
   * @return 字符串 yyyyMMdd HHmmss
   */
  public static String getStringToday() {
    Date currentTime = new Date();
    return formatter.format(currentTime);
  }

  /**
   * 字符串的日期格式的计算
   */
  public static int daysBetween(String smdate, String bdate) throws ParseException {
    Calendar cal;
    long between_days = 0;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
      cal = Calendar.getInstance();
      cal.setTime(formatter.parse(smdate));
      long time1 = cal.getTimeInMillis();
      cal.setTime(formatter.parse(bdate));
      long time2 = cal.getTimeInMillis();
      between_days = (time2 - time1) / (1000 * 3600 * 24);
    }

    return Integer.parseInt(String.valueOf(between_days));
  }

}
